package com.baor.service.impl;

import com.baor.dao.OrganizationDao;
import com.baor.domain.OrganizationVO;
import com.baor.service.OrganizationService;
import com.baor.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrganizationServiceImpl implements OrganizationService {
    @Autowired
    private OrganizationDao organizationDao;

    @Override
    public R getOrganizationTree() {
        try {
            List<OrganizationVO> allOrganizations = organizationDao.selectAllOrganizations();
            List<OrganizationVO> tree = buildTree(allOrganizations);
            return R.ok(tree);
        } catch (Exception e) {
            return R.er("获取机构树失败: " + e.getMessage());
        }
    }

    @Override
    public int update(OrganizationVO organization) {
        return this.organizationDao.updateById(organization);
    }

    @Override
    public int insert(OrganizationVO organization) {
        return this.organizationDao.insert(organization);
    }

    private List<OrganizationVO> buildTree(List<OrganizationVO> organizations) {
        // 使用Map来存储所有组织，key为id，value为组织对象
        Map<Long, OrganizationVO> organizationMap = organizations.stream()
                .collect(Collectors.toMap(OrganizationVO::getId, org -> org));

        // 构建树形结构
        List<OrganizationVO> rootOrganizations = organizations.stream()
                .filter(org -> {
                    Long parentId = org.getParentId();
                    // 如果parentId为null或0，或者父节点不存在于列表中，则认为是根节点
                    return parentId == null || parentId == 0 || !organizationMap.containsKey(parentId);
                })
                .peek(org -> setChildren(org, organizationMap))
                .collect(Collectors.toList());

        return rootOrganizations;
    }

    private void setChildren(OrganizationVO parent, Map<Long, OrganizationVO> organizationMap) {
        List<OrganizationVO> children = organizationMap.values().stream()
                .filter(org -> parent.getId().equals(org.getParentId()))
                .peek(org -> setChildren(org, organizationMap))
                .collect(Collectors.toList());

        if (!children.isEmpty()) {
            parent.setChildren(children);
        }
    }
}